package main

import "fmt"

// slice切片容量的追加/截取等操作
func main() {
    // 得到一个长度为3，但是容量为5的切片
    numbers := make([]int, 3, 5)
    fmt.Printf("len = %d, cap = %d, slice = %v\n", len(numbers), cap(numbers), numbers) // len = 3, cap = 5, slice = [0 0 0]

    // 在容量允许的范围内追加元素需要用到append关键字
    numbers = append(numbers, 3)
    numbers = append(numbers, 4)
    fmt.Printf("len = %d, cap = %d, slice = %v\n", len(numbers), cap(numbers), numbers) // len = 5, cap = 5, slice = [0 0 0 3 4]

    // 如果cap容量已满，这时候继续append，不会报错，而是会触发数组扩容，newCap = oldCap * 2
    numbers = append(numbers, 5)
    fmt.Printf("len = %d, cap = %d, slice = %v\n", len(numbers), cap(numbers), numbers) // len = 6, cap = 10, slice = [0 0 0 3 4 5]

    // 截取
    newNums := numbers[0:2]  // 从下标为0的元素开始，一直到下标为2的元素结束（左闭右开） = 包含0，不包含2 = [0:2) = [0,1]
    fmt.Printf("len = %d, cap = %d, newNums = %v\n", len(newNums), cap(newNums), newNums) // len = 2, cap = 10, newNums = [0 0]

    // 重要：newNums 和 numbers 指向的是同一片内存区间，一改均变
    newNums[0] = 111
    numbers[1] = 222
    fmt.Printf("len = %d, cap = %d, slice = %v\n", len(numbers), cap(numbers), numbers) // len = 6, cap = 10, slice = [111 222 0 3 4 5]
    fmt.Printf("len = %d, cap = %d, newNums = %v\n", len(newNums), cap(newNums), newNums) // len = 2, cap = 10, newNums = [111 222]

    // 如果想让newNums完全独立，则可以使用深拷贝copy，之后对切片进行改变，就不会再互相影响了！
    newNums2 := make([]int, 3)
    copy(newNums2, newNums)
    fmt.Printf("len = %d, cap = %d, newNums2 = %v\n", len(newNums2), cap(newNums2), newNums2) // len = 3, cap = 3, newNums2 = [111 222 0]
}